package org.itboys.core.service.mysql.web;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.coupon.SundayCouponReceiveMapper;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mysql.SundayCoupon;
import org.itboys.core.entity.mysql.SundayCouponReceive;
import org.itboys.core.service.mongo.web.SundayMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/8/30
 * @Description：优惠券领用
 */
@Service
public class SundayCouponReceiveService extends BaseMySqlService<SundayCouponReceive>{
    @Autowired
    private SundayCouponService couponService;
    @Autowired
    private SundayCouponReceiveMapper couponReceiveMapper;
    @Autowired
    private SundayMemberService memberService;

    public PageResult<SundayCouponReceive> select(HttpServletRequest request){
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request);
        //查询出所有的领用记录
        List<SundayCouponReceive> couponReceives = couponReceiveMapper.select(param);
        Set<Long> couponIds=new HashSet<>();
        Set<Long> memberIds=new HashSet<>();
        for (SundayCouponReceive c:couponReceives
             ) {
            couponIds.add(c.getCouponId());
            memberIds.add(c.getMemberId());
        }
        //查询出所有的用户信息
        Map<String,Object> _param=new HashedMap();
        _param.put("isDeleted", SundayCommonConstants.NO);
        _param.put("id in",memberIds);
        List<SundayMember> members = memberService.list(_param);
        _param.put("ids",couponIds);
        List<SundayCoupon> coupons = couponService.select(_param);
        for (SundayCouponReceive cr:couponReceives
             ) {
            cr.setReceiveDate(cr.getCreateDate());
            for (SundayMember m:members
                 ) {
                if(cr.getMemberId().equals(m.getId())){
                    cr.setMemberName(m.getNickName());
                    break;
                }
            }
            for (SundayCoupon c:coupons
                 ) {
                if(cr.getCouponId().equals(c.getId())){
                    cr.setCouponName(c.getName());
                    break;
                }
            }
        }
        return new PageResult<>(couponReceives,count(param));
    }
}
